package com.huoniu.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.huoniu.commons.utils.DateUtil;
import com.huoniu.facade.entity.user.UserEntity;
import com.huoniu.service.user.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/user")
public class UserRestController {

    @Reference(version = "1.0.0", interfaceClass = UserService.class)
    private UserService userService;

    @GetMapping(value = "/get/{id}")
    public Object getUserById(
            @PathVariable(value = "id") Integer id
    ) {
        return userService.selectById(id);
    }

    @GetMapping(value = "/list")
    public Object getUserByPage(int pageNo, int size) {
        Page<UserEntity> page = new Page<>(pageNo, size);
        page.setSearchCount(true);
        page.setOptimizeCountSql(true);
        EntityWrapper<UserEntity> wrapper = new EntityWrapper<>();
////        wrapper.like("name","张");
////        wrapper.gt("createtime", DateUtil.getInstance().stringToDate("2017-04-19 00:00:00")); // TODO 这个有问题
        long time = DateUtil.getInstance().stringToDate("2018-04-22 00:00:00").getTime()/1000;
        wrapper.where("age>={0}", 20);
        String sqlSegment = wrapper.getSqlSegment();
        System.out.println(sqlSegment);
        Page<UserEntity> userEntityPage = userService.selectPage(page, wrapper);
        userEntityPage.setTotal(userService.selectCount(wrapper));
        return userEntityPage;
    }

    @PostMapping(value = "save")
    public Object insertUser(String name, int age, String email) {
        UserEntity user = new UserEntity(name, email, age);
        return userService.insert(user);
    }

    @PostMapping(value = "/update")
    public Object updateUser(String name, int age, String email) {
        UserEntity user = new UserEntity(name, email, age);
        user.setId(1);
        return userService.updateById(user);
    }

    @GetMapping(value = "/delete")
    public boolean deleteUser(int id) {
        return userService.deleteById(id);
    }


    @GetMapping(value = "/count")
    public Object queryUserCount(){
        return userService.countUser();
    }


    @GetMapping("/getUserList")
    public Object testGetUserList(){

        EntityWrapper<UserEntity> wrapper = new EntityWrapper<>();
        wrapper.gt("age",12);

        List<UserEntity> userEntities = userService.selectList(wrapper);
        return userEntities;
    }

}
